package com.codewsq.exer.syn1;

/*
 * 实现Runnable的方式创建多线程,并完成三个窗口售票100张的需求
 * */
class WindowTicket implements Runnable {

    private int ticket = 100;
    private Object object = new Object();
    @Override
    public void run() {
        while (true) {
            // 方式一：任意类型的对象
//            synchronized (object){
            // 方式二：当前对象this
            synchronized (this) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}


public class TicketSalesToRunnable {
    public static void main(String[] args) {
        WindowTicket ticket = new WindowTicket();
        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}
